import cv2 as cv

videoFileName = r'F:AI\data\vtest.avi'
cap = cv.VideoCapture(videoFileName)
#Videocaptute函数中参数是0，表示打开笔记本前置摄像头；参数是路径，则按路径打开视频
f=cv.createBackgroundSubtractorMOG2()
#BackgroundSubtractor是专门用于视频分析的，会对每帧的环境进行学习。
#BackgroundSubtractor可以计算阴影，通过检测阴影，可排除检测图像阴影区域，从而关注实际特征
thresh = 200
while True:
    ret, frame =cap.read()
    if not ret: # 没读到当前帧，结束
        break

    fgmask = f.apply(frame)
    _, fgmask = cv.threshold(fgmask, 30, 0xff, cv.THRESH_BINARY)

    bgImage = f.getBackgroundImage()
    cnts, _ , _= cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    count = 0
    for c in cnts:
        area = cv.contourArea(c)  #有问题，未解决
        if (area < thresh):
            continue
        count += 1

        x, y, w, h = cv.boundingRect(c)
        cv.rectangle(frame, (x, y), (x + w, y + h), (0, 0xff, 0), 2)

    print('共检测到', count, '个目标', '\n')
    cv.imshow('frame', frame)
    cv.imshow('Background', bgImage)
    key = cv.waitKey(30)  # 每一帧间隔30ms
    if key == 27:  # 按下ESC键，退出
        break

cap.release()
cv.destroyAllWindows()

